package com.yunyao.framework.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yunyao.common.constant.enums.DataDeletedStatus;
import com.yunyao.common.dto.ReconciliationDto;
import com.yunyao.common.dto.ReconciliationOrderDto;
import com.yunyao.common.web.enums.ResultMsgEnum;
import com.yunyao.common.web.util.PageResult;
import com.yunyao.common.web.util.YResult;
import com.yunyao.dao.model.*;
import com.yunyao.dao.service.bamu.*;
import com.yunyao.framework.dto.reconciliation.*;
import com.yunyao.framework.dto.soSupply.SosupplySaveDto;
import com.yunyao.framework.service.ReconciliationOrderService;
import com.yunyao.framework.vo.reconciliation.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.validation.constraints.NotBlank;
import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ReconciliationOrderServiceImpl implements ReconciliationOrderService {
    @Autowired
    private IBamuReconciliationOrderMaterialService iBamuReconciliationOrderMaterialService;
    @Autowired
    private IBamuSoSupplyService iBamuSoSupplyService;
    @Autowired
    private IBamuReconciliationOrderService iBamuReconciliationOrderService;
    @Autowired
    private IBamuSoSupplyMaterialService iBamuSoSupplyMaterialService;
    @Resource
    private RedisTemplate<String, Integer> redisTemplate;

    @Override
    public YResult<ReconciliationOrderinfoVO> getReconliationOrderById(String id) {
        LambdaQueryWrapper<BamuReconciliationOrder> wrapper = new LambdaQueryWrapper<BamuReconciliationOrder>()
                .eq(BamuReconciliationOrder::getReconciliationId, id);
        BamuReconciliationOrder bamuReconciliationOrder = iBamuReconciliationOrderService.getOne(wrapper);
        // 处理查询结果
        if (Objects.isNull(bamuReconciliationOrder)) {
            return YResult.error(ResultMsgEnum.NO_DATA);
        }
        return YResult.success(daoToInfoVO(bamuReconciliationOrder));
    }


    private ReconciliationOrderinfoVO daoToInfoVO(BamuReconciliationOrder bamuReconciliation) {
        ReconciliationOrderinfoVO reconciliationinfoVO = new ReconciliationOrderinfoVO();
        BeanUtils.copyProperties(bamuReconciliation, reconciliationinfoVO);
        return reconciliationinfoVO;
    }

    @Override
    public YResult<PageResult<ReconciliationMaterialVO>> getReconciliationMaterialList(ReconciliationMaterialDto reconciliationMaterialDto) {
        // 构建查询条件
//        String contractId = reconciliationMaterialDto.getContractId();
////        String orderSn = reconciliationMaterialDto.getReconciliationOrderSn();
//        String purchaseApplyId = reconciliationMaterialDto.getPurchaseApplyId();
//        LambdaQueryWrapper<BamuReconciliationOrderMaterial> wrapper = new LambdaQueryWrapper<BamuReconciliationOrderMaterial>()
//                .eq(BamuReconciliationOrderMaterial::getContractId, contractId)
////                .eq(BamuReconciliationOrderMaterial::getPurchaseApplyId, purchaseApplyId)
//                .eq(BamuReconciliationOrderMaterial::getIsDeleted, DataDeletedStatus.NO.getType());

        LambdaQueryWrapper<BamuReconciliationOrderMaterial> queryWrapper = new LambdaQueryWrapper<BamuReconciliationOrderMaterial>()
                .eq(BamuReconciliationOrderMaterial::getIsDeleted, DataDeletedStatus.NO.getType())
                .eq(BamuReconciliationOrderMaterial::getReconciliationId, reconciliationMaterialDto.getReconciliationId())
                .orderByAsc(BamuReconciliationOrderMaterial::getMaterialSortNum);
        // 分页查询
        IPage<BamuReconciliationOrderMaterial> payPage = new Page<>(reconciliationMaterialDto.getPageIndex(), reconciliationMaterialDto.getPageSize());
        payPage = iBamuReconciliationOrderMaterialService.page(payPage, queryWrapper);

        // 处理查询结果
        if (CollectionUtils.isEmpty(payPage.getRecords())) {
            return YResult.success(new PageResult<>());
        }

        // 转换为VO对象列表
        List<ReconciliationMaterialVO> materialVOList = materialDaoToVoList(payPage.getRecords());

        // 返回分页结果
        return YResult.success(new PageResult<>(materialVOList, payPage.getCurrent(), payPage.getSize(), payPage.getPages(), payPage.getTotal()));

    }




    private List<ReconciliationMaterialVO> materialDaoToVoList(List<BamuReconciliationOrderMaterial> records) {
        return records.stream().map(this::materialDaoToVo).collect(Collectors.toList());
    }

    private ReconciliationMaterialVO materialDaoToVo(BamuReconciliationOrderMaterial bamuReconciliationOrderMaterial) {
        ReconciliationMaterialVO reconciliationMaterialVO = new ReconciliationMaterialVO();
        BeanUtils.copyProperties(bamuReconciliationOrderMaterial, reconciliationMaterialVO);
        reconciliationMaterialVO.setOrderSn(bamuReconciliationOrderMaterial.getReconciliationOrderSn());
        return reconciliationMaterialVO;
    }

    @Override
    public YResult<String> saveMaterialInfo(ReconciliationMaterSaveDto saveDto) {
        List<ReconciliationMaterialInfoSaveDto> dtoList = saveDto.getSaveDtoList();
        if (CollectionUtils.isEmpty(dtoList)) {
            return YResult.error(ResultMsgEnum.PARAM_ERROR);
        }
        List<BamuReconciliationOrderMaterial> daoList = materialDtoToDaoList(dtoList);
        if (CollectionUtils.isEmpty(daoList)) {
            return YResult.error(ResultMsgEnum.PARAM_ERROR);
        }
        iBamuReconciliationOrderMaterialService.saveOrUpdateBatch(daoList, 20);
        return YResult.success(saveDto.getContractId());
    }


    private List<BamuReconciliationOrderMaterial> materialDtoToDaoList(List<ReconciliationMaterialInfoSaveDto> dtoList) {
        return dtoList.stream().map(this::materialDtoToDao).collect(Collectors.toList());
    }

    private BamuReconciliationOrderMaterial materialDtoToDao(ReconciliationMaterialInfoSaveDto reconciliationMaterialInfoSaveDto) {
        BamuReconciliationOrderMaterial bamuReconciliationOrderMaterial = new BamuReconciliationOrderMaterial();
        BeanUtils.copyProperties(reconciliationMaterialInfoSaveDto, bamuReconciliationOrderMaterial);
        return bamuReconciliationOrderMaterial;
    }

    @Override
    public YResult<String> deletedMaterialInfo(ReconciliationMaterialDeleteDto deletedDto) {
        if (CollectionUtils.isEmpty(deletedDto.getIdList())) {
            return YResult.error(ResultMsgEnum.PARAM_ERROR);
        }
        List<BamuReconciliationOrderMaterial> updateList = Lists.newArrayList();
        for (String id : deletedDto.getIdList()) {
            BamuReconciliationOrderMaterial bamuReconciliationOrderMaterial = new BamuReconciliationOrderMaterial();
            bamuReconciliationOrderMaterial.setId(id);
            bamuReconciliationOrderMaterial.setIsDeleted(DataDeletedStatus.YES.getType());
            updateList.add(bamuReconciliationOrderMaterial);
        }
        iBamuReconciliationOrderMaterialService.updateBatchById(updateList, 20);
        return YResult.success(deletedDto.getContractId());
    }


    @Override
    public YResult<PageResult<ReconciliationOrderVO>> getReconciliationSoSupplyList(ReconciliationOrderDto reconciliationOrderDto) {
        // 构建查询条件
//        String contractId = reconciliationSoSupplyDto.getContractId();
//        String orderSn = reconciliationSoSupplyDto.getOrderSn();
//        LambdaQueryWrapper<BamuSoSupply> wrapper = new LambdaQueryWrapper<BamuSoSupply>()
//                .eq(BamuSoSupply::getContractId, contractId)
//                .eq(BamuSoSupply::getIsDeleted, DataDeletedStatus.NO.getType());
        // 分页查询
//        IPage<BamuSoSupply> payPage = new Page<>(reconciliationSoSupplyDto.getPageIndex(), reconciliationSoSupplyDto.getPageSize());
//        payPage = iBamuSoSupplyService.page(payPage, wrapper);


        LambdaQueryWrapper<BamuReconciliationOrder> queryWrapper =
                new LambdaQueryWrapper<BamuReconciliationOrder>().eq(BamuReconciliationOrder::getIsDeleted, DataDeletedStatus.NO.getType())
                        .eq(BamuReconciliationOrder::getReconciliationId, reconciliationOrderDto.getReconciliationId())
                        .orderByAsc(BamuReconciliationOrder::getId);
        // 分页查询
        IPage<BamuReconciliationOrder> settlementPage = new Page<>(reconciliationOrderDto.getPageIndex(), reconciliationOrderDto.getPageSize());
        settlementPage = iBamuReconciliationOrderService.page(settlementPage, queryWrapper);

        // 处理查询结果
        if (CollectionUtils.isEmpty(settlementPage.getRecords())) {
            return YResult.success(new PageResult<>());
        }

        // 转换为VO对象列表
        List<ReconciliationOrderVO> voList = orderDaoToVoList(settlementPage.getRecords());

        // 返回分页结果
        return YResult.success(new PageResult<>(voList, settlementPage.getCurrent(),
                settlementPage.getSize(), settlementPage.getPages(), settlementPage.getTotal()));
//        // 处理查询结果
//        if (CollectionUtils.isEmpty(payPage.getRecords())) {
//            return YResult.success(new PageResult<>());
//        }
//
//        // 转换为VO对象列表
//        List<ReconciliationSoSupplyVO> sosupplyVOList = sosupplyDaoToVoList(payPage.getRecords());
//
//        // 返回分页结果
//        return YResult.success(new PageResult<>(sosupplyVOList, payPage.getCurrent(), payPage.getSize(), payPage.getPages(), payPage.getTotal()));


    }


    /**
     * 根据合同id查询对账中的验收清单id
     *
     * @param contractId
     * @return
     */
    @Override
    public List<String> getSoSupply(@NotBlank String contractId) {
        List<BamuReconciliationOrder> list = iBamuReconciliationOrderService.lambdaQuery()
                .eq(BamuReconciliationOrder::getContractId, contractId)
                .eq(BamuReconciliationOrder::getIsDeleted, DataDeletedStatus.NO.getType())
                .list();
        if (CollectionUtils.isNotEmpty(list)) {
            return list.stream()
                    .map(BamuReconciliationOrder::getId)
                    .collect(Collectors.toList());
        }
        return null;
    }

    private List<ReconciliationOrderVO> orderDaoToVoList(List<BamuReconciliationOrder> records) {
        return records.stream().map(this::orderDaoToVo).collect(Collectors.toList());
    }

    private ReconciliationOrderVO orderDaoToVo(BamuReconciliationOrder bamuReconciliationOrder) {
        ReconciliationOrderVO reconciliationOrderVO = new ReconciliationOrderVO();
        BeanUtils.copyProperties(bamuReconciliationOrder, reconciliationOrderVO);
        return reconciliationOrderVO;
    }


    private List<BamuSoSupply> sosupplyDtoToDaoList(List<SosupplySaveDto> dtoList) {
        return dtoList.stream().map(this::sosupplyDtoToDao).collect(Collectors.toList());
    }

    private BamuSoSupply sosupplyDtoToDao(SosupplySaveDto soSupplyDto) {
        BamuSoSupply bamuSoSupply = new BamuSoSupply();
        BeanUtils.copyProperties(soSupplyDto, bamuSoSupply);
        return bamuSoSupply;
    }

    private List<ReconciliationSoSupplyVO> sosupplyDaoToVoList(List<BamuSoSupply> records) {
        return records.stream().map(this::sosupplyDaoToVo).collect(Collectors.toList());
    }

    private ReconciliationSoSupplyVO sosupplyDaoToVo(BamuSoSupply bamuSoSupply) {
        ReconciliationSoSupplyVO reconciliationSoSupplyVO = new ReconciliationSoSupplyVO();
        BeanUtils.copyProperties(bamuSoSupply, reconciliationSoSupplyVO);
        return reconciliationSoSupplyVO;
    }


    @Override
    public YResult<String> saveSoSupplyInfo(ReconciliationSoSupplySaveDto saveDto) {
        List<SosupplySaveDto> dtoList = saveDto.getSaveDtoList();
        if (CollectionUtils.isEmpty(dtoList)) {
            return YResult.error(ResultMsgEnum.PARAM_ERROR);
        }
        List<BamuSoSupply> daoList = sosupplyDtoToDaoList(dtoList);
        if (CollectionUtils.isEmpty(daoList)) {
            return YResult.error(ResultMsgEnum.PARAM_ERROR);
        }
        iBamuSoSupplyService.saveOrUpdateBatch(daoList, 20);
        return YResult.success(saveDto.getContractId());
    }

    @Override
    public YResult<String> deletedSoSupplyInfo(ReconciliationSoSupplyDeleteDto deletedDto) {
        if (CollectionUtils.isEmpty(deletedDto.getIdList())) {
            return YResult.error(ResultMsgEnum.PARAM_ERROR);
        }
        List<BamuSoSupply> updateList = Lists.newArrayList();
        for (String id : deletedDto.getIdList()) {
            BamuSoSupply bamuSoSupply = new BamuSoSupply();
            bamuSoSupply.setId(id);
            bamuSoSupply.setIsDeleted(DataDeletedStatus.YES.getType());
            updateList.add(bamuSoSupply);
        }
        iBamuSoSupplyService.updateBatchById(updateList, 20);
        return YResult.success(deletedDto.getContractId());
    }

    @Override
    public YResult<ReconciliationMaterialCountVO> getReconciliationMaterialCount(ReconciliationDto reconciliationDto) {
        try {
            // 提取合同ID
            String reconciliationId = reconciliationDto.getId();
            // 校验合同ID是否为空
            if (StringUtils.isBlank(reconciliationId)) {
                return YResult.error(ResultMsgEnum.PARAM_ERROR);
            }
            // 更新合同材料数量（具体实现略）
//            updateContractMaterialCount(contractId);
            // 初始化合同材料计数对象
            ReconciliationMaterialCountVO reconciliationMaterialCountVO = new ReconciliationMaterialCountVO();
//            // 获取合同材料总数
//            BigDecimal countSupplyNum = iBamuReconciliationOrderMaterialService.getSupplyNumByContractId(reconciliationId);
//            // 获取合同材料总价格
//            BigDecimal countComfirmSupplyNum = iBamuReconciliationOrderMaterialService.getComfirmSupplyNumByContractId(reconciliationId);
//            BigDecimal countIncludingTaxtotalPrice = iBamuReconciliationOrderMaterialService.getIncludingTaxTotalPriceByContractId(reconciliationId);
//            BigDecimal countReconciliationPrice = iBamuReconciliationOrderMaterialService.getReconciliationPriceByContractId(reconciliationId);
//            // 设置总数和总价格到VO对象
//            reconciliationMaterialCountVO.setCountSupplyNum(countSupplyNum);
//            reconciliationMaterialCountVO.setCountComfirmSupplyNum(countComfirmSupplyNum);
//            reconciliationMaterialCountVO.setCountIncludingTaxtotalPrice(countIncludingTaxtotalPrice);
//            reconciliationMaterialCountVO.setCountReconciliationPrice(countReconciliationPrice);
//            // 返回成功结果
//            return YResult.success(reconciliationMaterialCountVO);
            // 获取合同材料总数
            BigDecimal countSupplyNum = iBamuReconciliationOrderMaterialService.getSupplyNumByContractId(reconciliationId);
            if (countSupplyNum != null) {
                reconciliationMaterialCountVO.setCountSupplyNum(countSupplyNum);
            } else {
                reconciliationMaterialCountVO.setCountSupplyNum(null);
            }

// 获取合同材料总价格（这里假设是已确认的供应量，但变量名可能有些误导）
            BigDecimal countComfirmSupplyNum = iBamuReconciliationOrderMaterialService.getComfirmSupplyNumByContractId(reconciliationId);
            if (countComfirmSupplyNum != null) {
                reconciliationMaterialCountVO.setCountComfirmSupplyNum(countComfirmSupplyNum);
            } else {
                reconciliationMaterialCountVO.setCountComfirmSupplyNum(null);
            }

// 获取合同材料总价格（包含税）
            BigDecimal countIncludingTaxtotalPrice = iBamuReconciliationOrderMaterialService.getIncludingTaxTotalPriceByContractId(reconciliationId);
            if (countIncludingTaxtotalPrice != null) {
                reconciliationMaterialCountVO.setCountIncludingTaxtotalPrice(countIncludingTaxtotalPrice);
            } else {
                reconciliationMaterialCountVO.setCountIncludingTaxtotalPrice(null);
            }

// 获取合同材料对账价格
            BigDecimal countReconciliationPrice = iBamuReconciliationOrderMaterialService.getReconciliationPriceByContractId(reconciliationId);
            if (countReconciliationPrice != null) {
                reconciliationMaterialCountVO.setCountReconciliationPrice(countReconciliationPrice);
            } else {
                reconciliationMaterialCountVO.setCountReconciliationPrice(null);
            }

// 返回成功结果，即使某些值为null，VO对象仍会包含已设置的值
            return YResult.success(reconciliationMaterialCountVO);
        } catch (Exception ex) {
            // 捕获异常，返回系统错误信息
            return YResult.success(new ReconciliationMaterialCountVO());
        }
    }


//    private void updateContractMaterialCount(String contractId) {
//        // 根据合同ID查询销售合同，不包括已删除的记录
//        BamuReconciliation bamuSaleContract = ibamuSaleContractService.getByIdNoDelete(contractId);
//        // 如果找到了对应的销售合同
//        if (Objects.nonNull(bamuSaleContract)){
//            // 更新销售合同的总价和数量
//            ibamuSaleContractService.updateTotalPriceAndNumByContractId(contractId);
//            return;
//        }
//        // 如果未找到销售合同，则尝试查询采购合同
//        BamuPurchaseContract bamuPurchaseContract = iBamuPurchaseContractService.getByIdNoDelete(contractId);
//        // 如果找到了对应的采购合同
//        if (Objects.isNull(bamuPurchaseContract)){
//            return;
//        }
//        // 更新采购合同的总价和数量
//        iBamuPurchaseContractService.updateTotalPriceAndNumByContractId(contractId);
//    }
}
